﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DataControl;
using System.Net.Mail;
using System.Net;
using System.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using DAL.Dao;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Push;
using System.IO;
using iTextSharp.tool.xml;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Com.Alipay;

namespace BUS
{
    public class CommonHelp
    {
        Random rd = new Random();
        DataAccess da = new DataAccess();
        MessageDao Md = new MessageDao();
        JPush _push = new JPush();

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns>A.分供商 B.销售 C.客户</returns>
        public string GetInviteCode(string strType)
        {
            string strInvite = "";

            //生成随机10位码
            strInvite = GenerateRandom(5);

            if (strType == "A")
            {
                strInvite = strType + strInvite;
            }
            else if (strType == "B")
            {
                strInvite = strType + strInvite;
            }
            else
            {
               strInvite= constantCZ[rd.Next(1)].ToString() + strInvite;
            }

            //校验邀请码是否重复
            if (!CheckCode(strInvite))
            {
                GetInviteCode(strType);
            }
            LogDebug.Debug("GetInviteCode", strInvite);
            return strInvite;

        }
        /// <summary>
        /// 获取序列号
        /// </summary>
        /// <param name="type">2分供商订单号 1客户询价号</param>
        /// <returns></returns>
        public string GetSequence(string type)
        {
            string sequence = "";
            DataAccess da = new DataAccess();
            if (type == "2")
            {
                sequence += "FTX-S";
                sequence += DateTime.Now.ToString("yyyy").Substring(2, 2);
                string sql = "select count(*)num from t_contract where type='2' and CONVERT(nvarchar(4), create_time,111) =CONVERT(nvarchar(4), SYSDATETIME(),111)";
                object o = da.ExecuteScalar(sql);//本年
                if (o != null && o.ToString() != "")
                {
                    int _seq = int.Parse(o.ToString()) + 1;
                    sequence += _seq.ToString().PadLeft(4, '0');
                }
                else
                {
                    sequence += "0001";
                }
                return sequence;
            }
            if (type == "1")
            {
                sequence += "FTX-Q";
                sequence += DateTime.Now.ToString("yyyyMM");
                string sql = "select count(*)num from t_contract where type='1' and CONVERT(nvarchar(7), create_time,111) =CONVERT(nvarchar(7), SYSDATETIME(),111)";
                object o = da.ExecuteScalar(sql);//当月
                if (o != null && o.ToString() != "")
                {
                    int _seq = int.Parse(o.ToString()) + 1;
                    if (_seq <= 999)
                    {
                        sequence += _seq.ToString().PadLeft(3, '0');
                    }
                    else
                    {
                        sequence += _seq.ToString();
                    }
                }
                else
                {
                    sequence += "001";
                }
                return sequence;
            }
            return "";
        }

        #region 产生10位随机码
        //随机数 
        private static char[] constant = 
        { 
        '0','1','2','3','4','5','6','7','8','9'
        };

        //随机字母
        private static char[] constantCZ = 
        { 
        'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        };

        private static string GenerateRandom(int Length)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(10)]);
            }
            return newRandom.ToString();
        }
        #endregion

        /// <summary>
        /// 校验邀请码是否重复
        /// </summary>
        /// <param name="strInvite"></param>
        /// <returns></returns>
        private bool CheckCode(string strInvite)
        {
            DataAccess da = new DataAccess();
            string strSql = "";
            strSql = @"select count(1) count from T_SupplyCode where Code='{0}'";
            strSql = string.Format(strSql, strInvite);
            DataTable dtSCode = da.ExecuteDataTable(strSql);


            strSql = "";
            strSql = @"select count(1) count from T_AppUser where tauAdditional1='{0}'";
            strSql = string.Format(strSql, strInvite);
            DataTable dtAUser = da.ExecuteDataTable(strSql);

            if (dtSCode.Rows[0]["count"].ToString() == "0" && dtAUser.Rows[0]["count"].ToString() == "0")
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 获取提示信息
        /// </summary>
        /// <param name="strType">提示信息Id即类型</param>
        /// <param name="strLagId">语言Id</param>
        /// <returns></returns>
        public string GetTips(string strType, string strLagId)
        {
            DataAccess da = new DataAccess();
            string strTips = "";

            string strSql = "select * from D_tips_multiLan where Tips_ID='{0}' and LanId='{1}'";
            strSql = string.Format(strSql, strType, strLagId);
            DataTable dt = da.ExecuteDataTable(strSql);

            if (dt == null && dt.Rows.Count == 0)
            {

                return strTips;
            }
            else
            {
                strTips = dt.Rows[0]["Desc"].ToString();
                return strTips;
            }
        }

        /// <summary>
        /// 计算竞标推荐方案 Score=Price(60)+PayWay(5)+Deliver(5)+Technology(30)
        /// </summary>
        /// <param name="strtdiNo">需求Id</param>
        public List<BidScore> GetScore(string strtdiNo)
        {
            DataAccess da = new DataAccess();
            decimal dlMinPrice = 0;
            decimal intDeliverDay = 0;
            string strLevel = "";
            List<BidScore> ListBidScore = new List<BidScore>();
            BidScore EntryScore = new BidScore();
            string strCSupply = "";
            string strDSupply = "";

            //抓取产品C、D等级唯一供货商
            string strSqlCD = @"select distinct t1.level_c_supply,t1.level_d_supply
                            from T_DemandInformation t
                            inner join T_InformationCategory t1 on t.TicId=t1.TICID
                            where t.tdiNo='{0}'";
            strSqlCD = string.Format(strSqlCD, strtdiNo);
            DataTable dtCD = da.ExecuteDataTable(strSqlCD);
            if (dtCD != null && dtCD.Rows.Count > 0)
            {
                strCSupply = dtCD.Rows[0]["level_c_supply"].ToString();
                strDSupply = dtCD.Rows[0]["level_d_supply"].ToString();
            }


            //查询需求产品等级
            string strSqlLevel = @"select distinct t1.Level
                                from T_DemandInformationDetail t
                                inner join D_Item t1 on t.DiId=t1.DIID
                                where t.tdiNo='{0}'";
            strSqlLevel = string.Format(strSqlLevel, strtdiNo);
            DataTable dtLevel = da.ExecuteDataTable(strSqlLevel);
            if (dtLevel != null && dtLevel.Rows.Count > 0)
            {
                strLevel = dtLevel.Rows[0]["Level"].ToString().Trim();
            }

            //获取最低报价
            string strSqlMin = @"select t.tdiNo,min(t.tdibTotalPrice/t1.rate) MinPrice 
                        from T_DemandInformationBid t
                        inner join D_Currency t1 on t.tdibCurrency=t1.dcName
                        where t.tdiNo='{0}'
                        group by t.tdiNo";
            strSqlMin = string.Format(strSqlMin, strtdiNo);
            DataTable dt = da.ExecuteDataTable(strSqlMin);
            if (dt != null && dt.Rows.Count > 0)
            {
                dlMinPrice = Convert.ToDecimal(dt.Rows[0]["MinPrice"].ToString());
            }

            //获取系统货期即需求交货期
            string strSqlDay = @"select case t.tdiAdditional2 
	                   when '日' then t.tdiAdditional1
	                   when '月' then t.tdiAdditional1*30
	                   when '年' then t.tdiAdditional1*365
	                   end DeliverDay
                       from T_DemandInformation t
                       where t.tdiNo='{0}'";
            strSqlDay = string.Format(strSqlDay, strtdiNo);
            DataTable dtDay = da.ExecuteDataTable(strSqlDay);
            if (dtDay != null && dtDay.Rows.Count > 0)
            {
                intDeliverDay = Convert.ToDecimal(dtDay.Rows[0]["DeliverDay"].ToString());
            }

            //获取针对该需求竞价的所有投标数据
            string strSqlList = @"select t.TDIBID,t.tdiNo,t.tdibNo,t.TdiId,t.tdibPayType,t2.TAUID,
                                t.tdibTotalPrice/t1.rate RealTotalPrice,
                                case t.tdibDeliveryPeriodUnit 
                                when '日' then t.tdibDeliveryPeriod
                                when '月' then t.tdibDeliveryPeriod*30
                                when '年' then t.tdibDeliveryPeriod*365
                                end DeliverDay
                                from T_DemandInformationBid t
                                inner join D_Currency t1 on t.tdibCurrency=t1.dcName
                                inner join T_AppUser t2 on t.tauLoginId=t2.tauLoginId
                                where t.tdiNo='{0}'";

            strSqlList = string.Format(strSqlList, strtdiNo);
            DataTable dtList = da.ExecuteDataTable(strSqlList);
            if (dtList != null && dtList.Rows.Count > 0)
            {

                if (strLevel == "A")
                {
                    for (int i = 0; i < dtList.Rows.Count; i++)
                    {
                        EntryScore.TDIBID = Convert.ToInt32(dtList.Rows[i]["TDIBID"].ToString());
                        EntryScore.tdibNo = dtList.Rows[i]["tdibNo"].ToString();
                        EntryScore.tdiNo = dtList.Rows[i]["tdiNo"].ToString();
                        EntryScore.PriceWeight = GetPrice(dlMinPrice, Convert.ToDecimal(dtList.Rows[i]["RealTotalPrice"].ToString()));
                        EntryScore.PayWayWeight = GetPayWay(dtList.Rows[i]["tdibPayType"].ToString());
                        EntryScore.DeliverWeight = GetDeliver(intDeliverDay, Convert.ToDecimal(dtList.Rows[i]["DeliverDay"].ToString()));
                        EntryScore.TechnologyWeight = 30;
                        if (EntryScore.DeliverWeight == 999)
                        {
                            EntryScore.TotalScore = 0;
                            EntryScore.Memo = "交货期大于系统货期，流标";
                        }
                        else
                        {
                            EntryScore.TotalScore = EntryScore.PriceWeight + EntryScore.PayWayWeight + EntryScore.DeliverWeight + EntryScore.TechnologyWeight;
                        }

                        ListBidScore.Add(EntryScore);
                    }
                }
                else if (strLevel == "B")
                {
                    for (int i = 0; i < dtList.Rows.Count; i++)
                    {
                        EntryScore.TDIBID = Convert.ToInt32(dtList.Rows[i]["TDIBID"].ToString());
                        EntryScore.tdibNo = dtList.Rows[i]["tdibNo"].ToString();
                        EntryScore.tdiNo = dtList.Rows[i]["tdiNo"].ToString();
                        EntryScore.PriceWeight = GetPrice(dlMinPrice, Convert.ToDecimal(dtList.Rows[i]["RealTotalPrice"].ToString()));
                        EntryScore.PayWayWeight = 5;
                        EntryScore.DeliverWeight = 5;
                        EntryScore.TechnologyWeight = 30;
                        if (EntryScore.DeliverWeight == 999)
                        {
                            EntryScore.TotalScore = 0;
                            EntryScore.Memo = "交货期大于系统货期，流标";
                        }
                        else
                        {
                            EntryScore.TotalScore = EntryScore.PriceWeight + EntryScore.PayWayWeight + EntryScore.DeliverWeight + EntryScore.TechnologyWeight;
                        }

                        ListBidScore.Add(EntryScore);
                    }
                }
                else if (strLevel == "C")
                {
                    for (int i = 0; i < dtList.Rows.Count; i++)
                    {
                        EntryScore.TDIBID = Convert.ToInt32(dtList.Rows[i]["TDIBID"].ToString());
                        EntryScore.tdibNo = dtList.Rows[i]["tdibNo"].ToString();
                        EntryScore.tdiNo = dtList.Rows[i]["tdiNo"].ToString();
                        if (dtList.Rows[i]["TAUID"].ToString() == strCSupply)
                        {
                            EntryScore.PriceWeight = 60;
                            EntryScore.PayWayWeight = 5;
                            EntryScore.DeliverWeight = GetDeliver(intDeliverDay, Convert.ToDecimal(dtList.Rows[i]["DeliverDay"].ToString()));
                            EntryScore.TechnologyWeight = 30;
                            if (EntryScore.DeliverWeight == 999)
                            {
                                EntryScore.TotalScore = 0;
                                EntryScore.Memo = "交货期大于系统货期，流标";
                            }
                            else
                            {
                                EntryScore.DeliverWeight = 5;
                                EntryScore.TotalScore = EntryScore.PriceWeight + EntryScore.PayWayWeight + EntryScore.DeliverWeight + EntryScore.TechnologyWeight;
                            }
                        }
                        else
                        {
                            EntryScore.PriceWeight = 0;
                            EntryScore.PayWayWeight = 0;
                            EntryScore.DeliverWeight = 0;
                            EntryScore.TechnologyWeight = 0;
                            EntryScore.TotalScore = 0;
                            EntryScore.Memo = "不是指定供应商，流标";
                        }
                    }

                    ListBidScore.Add(EntryScore);

                }
                else if (strLevel == "D")
                {
                    for (int i = 0; i < dtList.Rows.Count; i++)
                    {
                        EntryScore.TDIBID = Convert.ToInt32(dtList.Rows[i]["TDIBID"].ToString());
                        EntryScore.tdibNo = dtList.Rows[i]["tdibNo"].ToString();
                        EntryScore.tdiNo = dtList.Rows[i]["tdiNo"].ToString();

                        if (dtList.Rows[i]["TAUID"].ToString() == strDSupply)
                        {
                            EntryScore.PriceWeight = 60;
                            EntryScore.PayWayWeight = 5;
                            EntryScore.DeliverWeight = GetDeliver(intDeliverDay, Convert.ToDecimal(dtList.Rows[i]["DeliverDay"].ToString()));
                            EntryScore.TechnologyWeight = 30;
                            if (EntryScore.DeliverWeight == 999)
                            {
                                EntryScore.TotalScore = 0;
                                EntryScore.Memo = "交货期大于系统货期，流标";
                            }
                            else
                            {
                                EntryScore.DeliverWeight = 5;
                                EntryScore.TotalScore = EntryScore.PriceWeight + EntryScore.PayWayWeight + EntryScore.DeliverWeight + EntryScore.TechnologyWeight;
                            }
                        }
                        else
                        {
                            EntryScore.PriceWeight = 0;
                            EntryScore.PayWayWeight = 0;
                            EntryScore.DeliverWeight = 0;
                            EntryScore.TechnologyWeight = 0;
                            EntryScore.TotalScore = 0;
                            EntryScore.Memo = "不是指定供应商，流标";
                        }
                    }
                    if (EntryScore.TotalScore == 0)
                    {//流标
                        string sql = "update T_DemandInformationBid set tdibRowSatus='4' where tdibno='" + EntryScore.tdibNo + "'";
                        da.ExcuteNoQuery(sql);
                    }

                    ListBidScore.Add(EntryScore);
                }
            }
            else
            {
                EntryScore.Memo = "无人竞标，流标";
                ListBidScore.Add(EntryScore);
            }

            return ListBidScore;

        }

        /// <summary>
        /// 获取价格权重
        /// </summary>
        /// <returns></returns>
        private decimal GetPrice(decimal dlMinPrice, decimal dlRealPrice)
        {
            decimal dlPrice = 0;
            if (dlMinPrice == dlRealPrice)
            {
                dlPrice = 60;
            }
            else
            {
                dlPrice = 60 - (dlRealPrice - dlMinPrice) / dlMinPrice * 100;
            }

            return dlPrice;
        }

        /// <summary>
        /// 获取付款方式权重
        /// </summary>
        /// <returns></returns>
        private decimal GetPayWay(string strPayWay)
        {
            decimal dlPayWay = 5;
            switch (strPayWay)
            {
                case "货到验收合格、票到90天付款":
                    dlPayWay = 5;
                    break;
                case "货到验收合格、票到30天付款":
                    dlPayWay = 4;
                    break;
                case "预付30%，货到现场30%，安装调试合格付30%，一年质保金10%":
                    dlPayWay = 1;
                    break;
                case "预付30%，发货前付70%":
                    dlPayWay = 0;
                    break;
            }

            return dlPayWay;
        }

        /// <summary>
        /// 获取交货期权重
        /// </summary>
        /// <returns></returns>
        private decimal GetDeliver(decimal dlSysDeliver, decimal dlDeliver)
        {
            decimal dlDeliverWeight = 5;
            decimal Rate = (dlDeliver - dlSysDeliver) / dlSysDeliver * 100;

            if (Rate < 0)
            {
                dlDeliverWeight = 7;
            }
            else if (Rate > 0 && Rate <= 10)
            {
                dlDeliverWeight = 5;
            }
            else if (Rate > 10 && Rate < 20)
            {
                dlDeliverWeight = 0;
            }
            else
            {
                dlDeliverWeight = 999;
            }


            return dlDeliverWeight;
        }



        /// <summary>
        /// 创建报价数据并推送消息
        /// </summary>
        /// <returns></returns>
        public bool CreateResAndSendMess(string strRequestID)
        {
            DataTable dt = new DataTable();
            Dictionary<string, object> parm = new Dictionary<string, object>();
            //查询每个子项
            string strSql = "";
            strSql = "select * from T_RequestDetail where RequestID='{0}'";
            strSql = string.Format(strSql, strRequestID);
            dt = da.ExecuteDataTable(strSql);

            //循环每个子项，检查是否有对应的分供商
            foreach (DataRow dr in dt.Rows)
            {
                parm = new Dictionary<string, object>();
                parm.Add("@ReqDetailID", dr["ReqDetailID"]);
                dt = da.GetDataTableBySPName("SP_CheckDetailSupply", parm);
                //没有合适的分供商，推送系统管理员
                if (dt == null || dt.Rows.Count == 0)
                {
                    //没有合适的供应商,推送系统管理员
                    #region 申明实体，并赋值
                    T_Message Entry = new T_Message();
                    Entry.tmType = "1";
                    Entry.tmfrom = "system";
                    Entry.tmto = "";
                    Entry.tmTitle = "无适配分供商";
                    Entry.tmMessage = Md.CreateMessageByRequestId(strRequestID, Entry.tmType);

                    //Entry.toType = "3";
                    //Entry.toId = contractid;

                    this.SendMessage(Entry, "2", new Dictionary<string, string>());
                    #endregion

                    return false;
                }
            }

            parm = new Dictionary<string, object>();
            parm.Add("@RequestID", strRequestID);

            dt = da.GetDataTableBySPName("SP_ChoiceSupply", parm);

            string strSql0 = @"update T_Request  set Is_Push='1'
                where RequestID='{0}'";
            strSql0 = string.Format(strSql0, strRequestID);
            da.ExcuteNoQuery(strSql0);

            foreach (DataRow dr in dt.Rows)
            {
                #region 申明实体，并赋值
                T_Message Entry = new T_Message();
                Entry.tmType = "3";
                Entry.tmfrom = "system";
                Entry.tmto = dr["tauloginid"].ToString();
                Entry.tmTitle = "询价单推送，请报价";
                Entry.tmMessage = Md.CreateMessageByRequestId(strRequestID, Entry.tmType);

                strSql = "";
                strSql = @"select t.ResponseID
                from T_Response t
                where t.tauloginid='{0}' and t.RequestID='{1}'";

                strSql = string.Format(strSql, dr["tauloginid"].ToString(), strRequestID);

                LogDebug.Debug("CreateResAndSendMess", strSql);
                DataTable dt1 = da.ExecuteDataTable(strSql);

                if (dt1 != null && dt1.Rows.Count > 0)
                {

                    Entry.toType = "2";
                    Entry.toId = dt1.Rows[0]["ResponseID"].ToString();

                    Dictionary<string, string> Parm = new Dictionary<string, string>();
                    Parm.Add("ResponseId", dt1.Rows[0]["ResponseID"].ToString());
                    this.SendMessage(Entry, "3", Parm);
                }



                #endregion
            }
            return true;
        }


        #region 格式转换
        /// <summary>
        /// DataTable转Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string ConvertDataTableToJSON(DataTable dt)
        {
            JArray jRtn = new JArray();
            if (dt == null || dt.Rows.Count == 0)
                return JsonConvert.SerializeObject(jRtn);

            foreach (DataRow row in dt.Rows)
            {
                JObject jRow = new JObject();
                for (int i = 0; i < dt.Columns.Count; i++)
                    jRow[dt.Columns[i].ColumnName] = ConvertToString(row[i]);

                jRtn.Add(jRow);
            }

            return JsonConvert.SerializeObject(jRtn);
        }

        public string ConvertToString(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return "";

            return obj.ToString();
        }
        public bool ConvertToBool(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return false;

            if (obj is bool)
                return (bool)obj;

            return false;
        }
        public int ConvertToInt(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return 0;

            int iRtn = 0;
            int.TryParse(obj.ToString(), out iRtn);
            return iRtn;
        }
        #endregion


        #region 推送信息
        //推送消息
        public bool SendMessage(T_Message TMessage, string strType, Dictionary<string, string> ParmKey)
        {
            DataAccess da = new DataAccess();
            bool blIsSend;
            bool blResult;
            int intResult = 0;
            JObject jo = new JObject();

            string strSql = @"INSERT INTO T_Message
                            (tmType,tmfrom,tmto,tmTitle,tmMessage,RowStatus,CreatedBy,CreatedDate,toType,toId)
                            VALUES
                            ('{0}','{1}','{2}',N'{3}',N'{4}',0,'system',GETDATE(),'{5}','{6}')";
            strSql = string.Format(strSql, TMessage.tmType, TMessage.tmfrom, TMessage.tmto, TMessage.tmTitle, TMessage.tmMessage, TMessage.toType, TMessage.toId);
            intResult = da.ExcuteNoQuery(strSql);



            #region 调用推送接口(待完善)

            //1.极光推送 2.邮箱推送 3.两者都推送
            switch (strType)
            {
                case "2":
                    intResult = this.SendEmailAsnyc(TMessage);
                    break;
                case "3":

                    //邮件推送
                    intResult = this.SendEmailAsnyc(TMessage);
                    if (ParmKey.ContainsKey("ContractId") || ParmKey.ContainsKey("RequestId") || ParmKey.ContainsKey("ResponseId"))
                    {
                        //极光推送
                        _push.PushByAlias(TMessage.tmto, TMessage.tmMessage, ParmKey);
                    }
                    else
                    {
                        //极光推送
                        _push.PushByAlias(TMessage.tmto, TMessage.tmMessage);
                    }
                    break;
            }

            if (intResult != -1)
            {
                //da.ExecuteDataTable(
                //string.Format("update T_Message set RowStatus=1 where tmType='{0}' and tmfrom='{1}' and tmto='{2}' and tmMessage='{3}' and CreatedDate='{4}'",
                //TMessage.tmType, TMessage.tmfrom, TMessage.tmto, TMessage.tmMessage, TMessage.CreatedDate));
                blIsSend = true;
            }
            else
            {
                blIsSend = false;
            }
            #endregion

            if (intResult == 1 && blIsSend == true)
            {
                blResult = true;
            }
            else
            {
                blResult = false;
            }



            if (blResult)
            {
                return true;
            }
            else
            {
                return false;
            }

        }


        /// <summary>
        /// 邮箱发送消息
        /// </summary>
        /// <param name="strLogin">收件人登录Id</param>
        /// <param name="strType">邮件类型:9+ </param>
        /// <param name="strType">内容</param>
        private int SendEmailAsnyc(T_Message TMessage)
        {
            try
            {
                string pToEmail = "";
                int RandKey = 0;
                DataAccess da = new DataAccess();


                //SmtpClient client = new SmtpClient("mail.antiwearvalve.com",25);
                SmtpClient client = new SmtpClient();
                #region 邮箱发件人 tmfrom

                #region 测试环境
                client.Host = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailHost"]) ? "smtp.exmail.qq.com" : ConfigurationManager.AppSettings["EmailHost"];
                client.Port = 25;

                client.EnableSsl = false;

                string mFrom = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailFrom"]) ? "moose.zhang@ztnet.com.cn" : ConfigurationManager.AppSettings["EmailFrom"];
                string mPassword = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailFromPwd"]) ? "Zsh768594" : ConfigurationManager.AppSettings["EmailFromPwd"];
                string mDisplayName = "Antiwear";
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(mFrom, mPassword);//用户名和密码         
                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(mFrom, mDisplayName, System.Text.Encoding.UTF8);
                #endregion

                #region 正式环境

                //client.Host = "mail.antiwearvalve.com";
                //client.Port = 25;
                //client.EnableSsl = false;
                ////string mFrom = "antiwearvalve.com\\crm_service"; 
                ////string mPassword = "82880588"; 
                ////string mDisplayName = "Antiwear";
                //client.UseDefaultCredentials = false;

                //client.DeliveryMethod = SmtpDeliveryMethod.Network;
                //MailMessage mail = new MailMessage();
                //mail.From = new System.Net.Mail.MailAddress("crm_service@antiwearvalve.com", "Antiwear", System.Text.Encoding.UTF8);
                #endregion


                //mail.From = new MailAddress(mFrom, mDisplayName, System.Text.Encoding.UTF8);         
                //mail.To.Add("jinjie@antiwearvalve.com");

                #endregion

                #region 邮件收件人 tmto
                if (TMessage.tmType == "1")
                {
                    DataTable dt = GetMsgReceiver();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            mail.To.Add(new MailAddress(dr["value"].ToString()));
                        }
                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    DataTable dt = GetLoginEmail(TMessage.tmto);
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        return -1;
                    }
                    else
                    {
                        pToEmail = dt.Rows[0]["tauEmail"].ToString();
                    }

                    mail.To.Add(new MailAddress(pToEmail));
                }

                #endregion

                #region 邮件标题 tmTitle
                mail.Subject = string.IsNullOrWhiteSpace(TMessage.tmTitle) ? "安特威推送服务" : TMessage.tmTitle;
                #endregion

                #region 邮件内容 tmMessage
                //switch (TMessage.tmType)
                //{
                //    //推送默认管理员
                //    case "1":
                //        break;
                //    //推送客户
                //    case "2":
                //        break;
                //    //推送分供商
                //    case "3":
                //        break;
                //    //销售推送消息
                //    case "4":
                //        break;

                //}

                if (string.IsNullOrWhiteSpace(TMessage.tmMessage))
                {
                    DataTable dtMessage = da.ExecuteDataTable(string.Format("select dfValue from D_Foundation where dfType ='{0}'", TMessage.tmMessage));
                    if (dtMessage == null || dtMessage.Rows.Count <= 0)
                        return -1;

                    mail.Body = dtMessage.Rows[0]["dfValue"].ToString();
                }
                else
                {
                    mail.Body = TMessage.tmMessage;
                }
                #endregion





                client.Send(mail);

                return 1;
            }
            catch (Exception ex)
            {

                return -1;

                //Log
                //Util.WriteLog(Server, "SendMail EX:" + ex.Message);
            }
        }
        public int SendEmail(string targetAddress, string content)
        {
            try
            {
                SmtpClient client = new SmtpClient();
                client.Host = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailHost"]) ? "smtp.exmail.qq.com" : ConfigurationManager.AppSettings["EmailHost"];
                client.Port = 25;

                client.EnableSsl = false;

                string mFrom = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailFrom"]) ? "moose.zhang@ztnet.com.cn" : ConfigurationManager.AppSettings["EmailFrom"];
                string mPassword = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailFromPwd"]) ? "Zsh768594" : ConfigurationManager.AppSettings["EmailFromPwd"];
                string mDisplayName = "安特威";
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(mFrom, mPassword);//用户名和密码         
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(mFrom, mDisplayName, System.Text.Encoding.UTF8);
                mail.To.Add(new MailAddress(targetAddress));
                mail.Subject = "测试";
                mail.Body = content;
                client.Send(mail);
            }
            catch (Exception ex)
            {
                return -1;
            }
            return 0;
        }
        /// <summary>
        /// 获取默认邮件管理人员地址
        /// </summary>
        /// <returns></returns>
        private DataTable GetMsgReceiver()
        {

            DataAccess da = new DataAccess();
            string strSql = "select value from D_SystemArgs where [key]='DefaultMsgReceiver' and rowstatus!=2";
            DataTable dt = da.ExecuteDataTable(strSql);

            return dt;
        }

        /// <summary>
        /// 获取目标邮箱地址
        /// </summary>
        /// <param name="strLoginId"></param>
        /// <returns></returns>
        private DataTable GetLoginEmail(string strLoginId)
        {
            DataAccess da = new DataAccess();
            string strSql = "select tauEmail from T_AppUser where tauLoginId='{0}'";

            strSql = string.Format(strSql, strLoginId);

            return da.ExecuteDataTable(strSql);
        }

        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
            else
            {
                return true;
            }
        }
        #endregion




        /// <summary>
        /// 生成PDF文档
        /// </summary>
        /// <param name="resorce"></param>
        /// <param name="savePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool GeneretePdf(string htmlResorce, out string fileName)
        {
            fileName = "";
            try
            {
                MemoryStream inputStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlResorce));//转化输入流
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000).ToString() + ".pdf";//文件名
                string filePath = ConfigurationManager.AppSettings["pdfFilePath"];//路径
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);//目录结构
                }
                Document pdf = new Document(PageSize.A4, 50, 50, 50, 50);//pdf文件的大小，边距

                PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(filePath + fileName, FileMode.Create));

                PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, pdf.PageSize.Height, 1f);
                pdf.Open();
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdf, inputStream, null, Encoding.UTF8, new UnicodeFontFactory());
                PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);
                pdf.Close();
                return true;
            }
            catch (Exception ex)
            {
                Log.Debug("pdf", ex.Message.ToString());
            }
            return false;
        }

        //设置字体类  
        public class UnicodeFontFactory : FontFactoryImp
        {
            private static readonly string arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
      "arialuni.ttf");//arial unicode MS是完整的unicode字型。  
            private static readonly string 标楷体Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
            "KAIU.TTF");//标楷体  


            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
            {
                BaseFont bfChiness = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //可用Arial或标楷体，自己选一个  
                //BaseFont baseFont = BaseFont.CreateFont(标楷体Path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                return new Font(bfChiness, size, style, color);
            }
        }

       
    }
}
